package studychinese.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.widget.GlideCircleTransform;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.OptionPicker;
import cn.qqtheme.framework.widget.WheelView;
import de.hdodenhof.circleimageview.CircleImageView;
import studychinese.activity.LeaveMessageActivity;
import studychinese.activity.LoginActivity;
import studychinese.activity.PersonalInformationActivity;
import studychinese.activity.SettingActivity;
import studychinese.callback.DialogCallback;
import studychinese.config.AppUrl;
import studychinese.config.ConFigTag;
import studychinese.config.Url;
import studychinese.model.RegisterBean;
import studychinese.model.UserBean;
import studychinese.model.WhyStudayCZFBean;
import studychinese.utils.AppUtils;
import studychinese.utils.TimeUtil;


/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends BaseFragment {


    @Bind(R.id.tv_mysetting_time)
    TextView tvMysettingTime;
    @Bind(R.id.tv_my_nikename)
    TextView tv_my_nikename;
    @Bind(R.id.iv_my_photo_icon)
    ImageView iv_my_photo_icon;
    public MyFragment() {
        // Required empty public constructor
    }


    public static MyFragment newInstance() {

        Bundle args = new Bundle();

        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my, container, false);
        ButterKnife.bind(this, rootView);

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        getPersonInfo();
    }

    private void getPersonInfo() {
        OkGo.<String>post(AppUrl.getAppUrl(Url.REGISTER_GETUSERMASSAGE)).params("user_id", UserBean.getInfor().getUser_id()).execute(new DialogCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                RegisterBean registerBean = JSON.parseObject(response.body(), RegisterBean.class);
                if(registerBean.getState().equals(ConFigTag.state)){
                    RegisterBean.DataBean data = registerBean.getData();
                    String user_image = data.getUser_image();
                    UserBean.putUserBean(data);
                    tvMysettingTime.setText(data.getLearn_time());
                    if(data.getUser_nickname().equals("")){
                        tv_my_nikename.setText("用户"+TimeUtil.Tests1(registerBean.getData().getCreate_time()));
                    }else {
                        tv_my_nikename.setText(data.getUser_nickname());
                    }
                    if("".equals(user_image)){
                        Glide.with(getActivity()).load(R.mipmap.my_photo_normal).into(iv_my_photo_icon);
                    }else {
                        Glide.with(getActivity())
                                .load(user_image)
                                .transform(new CenterCrop(getContext()),new GlideCircleTransform(getContext()))
                                .crossFade()
                                .into(iv_my_photo_icon);
                    }
                }
            }
        });
    }

    public void initSeleteTime(final List<WhyStudayCZFBean.DataBean> data) {
        final List<String> list = new ArrayList<>();
        list.clear();
        for (int i = 0; i < data.size(); i++) {
            list.add(data.get(i).getName());
        }
        OptionPicker picker = new OptionPicker(getActivity(), list);
        String s = tvMysettingTime.getText().toString();
        if(!s.equals("")){
            picker.setSelectedItem(s);
        }

        picker.setCycleDisable(true);
        picker.setOffset(2);
        picker.setCancelTextColor(Color.WHITE);
        picker.setCancelTextSize(13);
        picker.setSubmitTextColor(Color.WHITE);
        picker.setTopLineColor(Color.WHITE);
        picker.setSubmitTextSize(13);
        picker.setBackgroundColor(getActivity().getResources().getColor(R.color.back_theme));
        picker.setTopBackgroundColor(getActivity().getResources().getColor(R.color.back_theme));
        picker.setDividerVisible(true);
        picker.setLineSpaceMultiplier(3);
        picker.setDividerColor(Color.WHITE);
        picker.setTextSize(16);
        picker.setLineColor(Color.WHITE);
        picker.setTextColor(Color.WHITE, Color.WHITE);
        picker.setCycleDisable(true);
        WheelView.DividerConfig config = new WheelView.DividerConfig();
        config.setRatio(0);
        config.setAlpha(100);
        config.setThick(1);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener(

        ) {
            @Override
            public void onOptionPicked(int index, String item) {
               // ToastUtils.showShort("index=" + index + ", item=" + item);
                NetDate(data.get(index).getId(),data.get(index).getName());
            }
        });
        picker.setOnWheelListener(new OptionPicker.OnWheelListener() {
            @Override
            public void onWheeled(int index, String item) {
              //  ToastUtils.showShort("index=" + index + ", item=" + item);
            }
        });
        //得到选择器视图，可内嵌到其他视图容器，不需要调用show方法


        picker.show();
    }

    private void NetDate(final String index, final String learnName) {
        OkGo.<String>post(AppUrl.getAppUrl(Url.REGISTER_UPDATEUSERINFO)).params("user_id", UserBean.getInfor().getUser_id()).params("learn_time", index).
                execute(new DialogCallback<String>() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject obj = new JSONObject(response.body());
                            String state = obj.getString("state");
                            String message = obj.getString("message");
                            if (state.equals("0")) {

                                tvMysettingTime.setText(learnName);
                                RegisterBean.DataBean infor = UserBean.getInfor();
                                infor.setLearn_time(index);
                                UserBean.putUserBean(infor);

                            } else {

                            }
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.iv_my_setting_icon, R.id.iv_my_photo_icon, R.id.rl_my_photo, R.id.rl_learning_Achievement, R.id.rl_slearning_plan, R.id.rl_learning_help, R.id.rl_leave_message})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_my_setting_icon:
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            case R.id.iv_my_photo_icon:
                break;
            case R.id.rl_my_photo:
                if(AppUtils.isLogin()){
                    startActivity(new Intent(getActivity(),PersonalInformationActivity.class));
                }else {
                    startActivity(new Intent(getActivity(),LoginActivity.class));
                }

                break;
            case R.id.rl_learning_Achievement:

                break;
            case R.id.rl_slearning_plan:
                setData();
                break;
            case R.id.rl_learning_help:
                break;
            case R.id.rl_leave_message:
                startActivity(new Intent(getActivity(), LeaveMessageActivity.class));
                break;


        }
    }


    private void setData() {
        OkGo.<WhyStudayCZFBean>post(AppUrl.getAppUrl(Url.REGISTER_USERLEARNTIME)) .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new DialogCallback<WhyStudayCZFBean>(getActivity(),true) {
                    @Override
                    public void onSuccess(Response<WhyStudayCZFBean> response) {
                        WhyStudayCZFBean body = response.body();
                        if(body.getState().equals(ConFigTag.state)){
                            List<WhyStudayCZFBean.DataBean> data = body.getData();
                            initSeleteTime(data);
                        }
                    }
                });
    }


}
